<template>
  <div style="margin-left: 20px">
    <a-row style="margin: 20px" :gutter="20">
      <a-col :span="6">
        <a-select
          ref="select"
          v-model:value="searchForm.xzName"
          @focus="focus"
          @change="selectXZname"
          placeholder="请选择社区"
          style="width: 200px"
        >
          <a-select-option v-for="item in districtList1" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        <a-select ref="select" v-model:value="searchForm.shName" @focus="focus" style="width: 200px" placeholder="请选择街道">
          <a-select-option v-for="item in streetList" :value="item" :key="item">{{ item }}</a-select-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        <a-input v-model:value="searchForm.keyword" placeholder="订单编号、用户ID、姓名、手机号"></a-input>
      </a-col>
      <a-col :span="2" :offset="1">
        <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
      </a-col>
    </a-row>

    <a-button style="margin-bottom: 20px" type="primary" @click="openModal('visible')" v-has="{ a: $route, b: 2 }" class="d-a-center"
      >新增拼团</a-button
    >
    <a-table
      :columns="colums"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="rowSelection"
      :scroll="{ y: 540, x: 'auto' }"
      :scrollToFirstRowOnChange="true"
    >
      <template #operation="{ record }">
        <div>
          <a-button type="link" @click="look(record.id)" v-has="{ a: $route, b: 1 }">查看</a-button>
          <a-button type="link" danger @click="del(record.id)" style="margin-left: 10px" v-has="{ a: $route, b: 2 }">删除</a-button>
        </div>
      </template>
    </a-table>

    <a-modal :visible="visible" title="新增拼团" @ok="addGroup" @cancel="closeModal('visible')">
      <a-form :model="form" ref="formRef" :rules="rules" :label-col="labelCol">
        <a-form-item label="拼团名称" name="hdName">
          <a-input placeholder="请输入拼团名称" v-model:value="form.hdName"></a-input>
        </a-form-item>
        <a-form-item label="服务价格" name="price">
          <a-input-number placeholder="请输入服务价格" v-model:value="form.price" :min="0.01"></a-input-number>
        </a-form-item>
        <a-form-item label="行政社区" name="xzName">
          <a-select ref="select" v-model:value="form.xzName" @focus="focus" placeholder="请选择社区">
            <a-select-option v-for="item in districtList" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="街道" name="shName">
          <a-input-group>
            <a-auto-complete
              v-model:value="form.shName"
              :options="addressList"
              style="width: 100%"
              @input="searchAddress"
              placeholder="请输入街道"
            />
          </a-input-group>
        </a-form-item>
        <a-form-item label="基础人数" name="num">
          <a-input-number v-model:value="form.num" placeholder="基础人数" :min="1"></a-input-number>
        </a-form-item>
        <a-form-item label="限制人数" name="astrictNum">
          <a-input-number v-model:value="form.astrictNum" placeholder="限制人数" :min="1"></a-input-number>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal :visible="lookVisible" @ok="closeModal('lookVisible')" title="查看" @cancel="closeModal('lookVisible')" width="70%">
      <a-descriptions bordered :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }">
        <a-descriptions-item label="拼团名称">{{ detail.hdName }}</a-descriptions-item>
        <a-descriptions-item label="服务价格">{{ detail.price }}</a-descriptions-item>
        <a-descriptions-item label="行政社区">{{ detail.xzName }}</a-descriptions-item>

        <a-descriptions-item label="街道">{{ detail.shName }}</a-descriptions-item>
        <a-descriptions-item label="基础人数">{{ detail.num }}</a-descriptions-item>
        <a-descriptions-item label="限制人数">{{ detail.astrictNum }}</a-descriptions-item>
        <a-descriptions-item label="实际人数">{{ detail.realNum }}</a-descriptions-item>
      </a-descriptions>

      <a-row style="padding: 20px; align-items: center; background-color: #e6e6e6; font-weight: bold">
        <a-col :span="24" style="margin-bottom: 20px"> 实际参与人数列表 </a-col>
        <a-row :gutter="20">
          <a-col :span="8">
            <a-select ref="select" v-model:value="searchDetailForm.status" @focus="focus" placeholder="请选择订单状态">
              <a-select-option v-for="item in statusList" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="8">
            <a-input placeholder="请输入姓名" v-model:value="searchDetailForm.name"></a-input>
          </a-col>
          <a-col :span="8">
            <a-input placeholder="请输入手机号" v-model:value="searchDetailForm.mobile"></a-input>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px" :gutter="20">
          <a-col :span="6">
            <a-input placeholder="请输入订单编号" v-model:value="searchDetailForm.number"></a-input>
          </a-col>
          <a-col :span="12">
            <a-range-picker v-model:value="time" showTime @change="selectTime" style="width: 100%" format="YYYY-MM-DD HH:mm:ss" />
          </a-col>
          <a-col :span="2" :offset="1">
            <a-button type="primary" @click="searchUser" class="d-a-center">搜索</a-button>
          </a-col>
        </a-row>
      </a-row>

      <a-table
        :columns="colums1"
        :data-source="userList"
        bordered
        :loading="loading1"
        :pagination="pagination1"
        @change="handleTableChange1"
        :row-selection="rowSelection1"
        :scroll="{ y: 540, x: 'auto' }"
        :scrollToFirstRowOnChange="true"
      >
        <template #operation="{ record }">
          <div style="display: flex; flex-wrap: wrap; min-width: 100px">
            <a-button type="link" danger @click="refund(record.id)" v-if="record.status == 1" v-has="{ a: $route, b: 2 }">退款</a-button>
            <a-button type="link" v-if="record.status == 1" @click="confirm(record.id)" v-has="{ a: $route, b: 2 }">完成</a-button>
          </div>
        </template>
        <template #status="{ record }">
          <a-tag :color="orderListStatusColor(record.status)">
            {{ orderStatus(record.status) }}
          </a-tag>
        </template>
        <template #price="{ record }">
          <div>
            {{ record.price ? record.price : '未支付' }}
          </div>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { reactive, createVNode, toRefs, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined, EditOutlined } from '@ant-design/icons-vue'
import { throttle } from '@/assets/js/debounceThrottle'
import axios from 'axios'
import { deleteObjBlank } from '@/assets/js/common.js'
import { useModal } from '@/hooks'
import { selectById, deleteOrder, selectPromotionOrder, createOrder, cancelById, selectAllshName } from '@/api/order/index'
export default {
  setup() {
    const data = reactive({
      list: [],
      loading: true,
      loading1: true,
      visible: false,
      lookVisible: false,
      form: {},
      formRef: '',
      addressList: [],
      detail: {}, //详情
      userList: [], //用户列表
      time: [],
      searchDetailForm: {}, //用户列表搜索表单
      value: '',
      searchForm: {}, //查询团
      streetList: [] //街道列表
    })
    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    const page1 = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    const rules = reactive({
      price: [{ required: true, message: '请输入价格' }],
      hdName: [{ required: true, message: '请输入拼团名称', trigger: 'blur' }],
      xzName: [{ required: true, message: '请输入街道名称', trigger: 'blur' }],
      num: [{ required: true, message: '请输入基础人数' }],
      astrictNum: [{ required: true, message: '请输入限制人数' }],
      shName: [{ required: true, message: '请选择行政区名', trigger: 'blur' }]
    })

    // 状态列表
    const districtList = [
      {
        name: '余杭区',
        id: '余杭区'
      },
      {
        name: '西湖区',
        id: '西湖区'
      },
      {
        name: '萧山区',
        id: '萧山区'
      },
      {
        name: '拱墅区',
        id: '拱墅区'
      },
      {
        name: '滨江区',
        id: '滨江区'
      },
      {
        name: '上城区',
        id: '上城区'
      }
    ]
    const districtList1 = [
      {
        name: '全部',
        id: '全部'
      },
      {
        name: '余杭区',
        id: '余杭区'
      },
      {
        name: '西湖区',
        id: '西湖区'
      },
      {
        name: '萧山区',
        id: '萧山区'
      },
      {
        name: '拱墅区',
        id: '拱墅区'
      },
      {
        name: '滨江区',
        id: '滨江区'
      },
      {
        name: '上城区',
        id: '上城区'
      }
    ]
    const getDistrictList = e => {
      if (e) {
        districtList.unshift({ name: '全部', id: '全部' })
        return districtList
      } else {
        return districtList
      }
    }
    const statusList = [
      {
        name: '已报名',
        id: 1
      },
      {
        name: '已完成',
        id: 2
      },
      {
        name: '已退款',
        id: 3
      }
    ]
    const orderStatus = status => {
      let title = ''
      switch (status) {
        case 0:
          title = '未报名'
          break
        case 1:
          title = '已报名'
          break
        case 2:
          title = '已完成'
          break
        case 3:
          title = '已退款'
          break
        default:
          break
      }
      return title
    }

    const colums = [
      {
        title: '编号',
        dataIndex: 'number',
        className: 'table'
      },
      {
        title: '拼团名称',
        dataIndex: 'hdName',
        className: 'table'
      },
      {
        title: '行政社区',
        dataIndex: 'xzName',
        className: 'table'
      },
      {
        title: '服务价格',
        dataIndex: 'price',
        className: 'table',
        slots: {
          customRender: 'price'
        }
      },
      {
        title: '实际参与人数',
        dataIndex: 'realNum',
        className: 'table'
      },

      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        fixed: 'right',
        // width: 150,
        // align: "center",
        slots: {
          customRender: 'operation'
        }
      }
    ]
    const colums1 = [
      {
        title: '订单编号',
        dataIndex: 'number',
        className: 'table'
      },
      {
        title: '用户姓名',
        dataIndex: 'nick',
        className: 'table'
      },
      {
        title: '用户ID',
        dataIndex: 'userId',
        className: 'table'
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        className: 'table'
      },
      {
        title: '人数',
        dataIndex: 'num',
        className: 'table'
      },
      {
        title: '服务地址',
        dataIndex: 'address',
        className: 'table'
      },
      {
        title: '服务时间',
        dataIndex: 'scheduleTime',
        className: 'table'
      },
      {
        title: '支付金额',
        dataIndex: 'price',
        className: 'table'
      },
      {
        title: '状态',
        dataIndex: 'status',
        className: 'table',
        slots: {
          customRender: 'status'
        }
      },

      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        fixed: 'right',
        width: 150,
        // align: "center",
        slots: {
          customRender: 'operation'
        }
      }
    ]
    const orderListStatusColor = computed(status => {
      return function (status) {
        if (status == 0) {
          return '#f50'
        }
        if (status == 1) {
          return 'success'
        }
        if (status == 2) {
          return 'cyan'
        }
        if (status == 3) {
          return 'warning'
        }
      }
    })
    // 分页器/-
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))
    const pagination1 = computed(() => ({
      current: page1.current,
      pageSize: page1.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page1.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))
    const selectTime = (e, dateString) => {
      console.log(dateString, '时间是-----')
      data.searchDetailForm.startTime = dateString[0]
      data.searchDetailForm.endTime = dateString[1]
    }
    const search = () => {
      page.current = 1
      init()
    }
    const openModal = e => {
      data[e] = true
    }
    const closeModal = e => {
      data[e] = false
    }
    const addGroup = () => {
      console.log(data.form, '表单内容是')
      data.formRef.validate().then(async () => {
        let res = await createOrder(data.form)
        if (res.success) {
          message.success('新增拼团成功')
          closeModal('visible')
          init()
        }
      })
    }
    const searchAddress = throttle(
      async () => {
        let url = 'https://restapi.amap.com/v3/place/text?key=77414f92d5cde517e199c03ab4258fda'
        let res = await axios.get(`${url}&keywords=${data.form.address}&city=杭州&citylimit=true`)
        res.data.pois.forEach(el => (el.value = el.adname + el.address))
        data.addressList = res.data.pois
        // console.log(data.addressList, "地址列表是");
      },
      500,
      true
    )
    const searchUser = () => {
      lookDetail()
    }
    const look = async id => {
      data.searchDetailForm.id = id
      lookDetail()
      openModal('lookVisible')
      //   let res = await selectById({ id });
      //   if (res.success) {
      //     data.userList = res.data;
      //     data.detail = res.object;
      //   }
    }
    async function lookDetail() {
      deleteObjBlank(data.searchDetailForm)
      let obj = {
        ...data.searchDetailForm,
        pageNum: page1.current,
        pageSize: page1.pageSize
      }
      let res = await selectById(obj)
      if (res.success) {
        res.data.list.map(el => (el.key = el.id))
        data.loading1 = false
        data.userList = res.data.list
        data.detail = res.object
        page1.total = res.data.total
      }
    }
    const del = id => {
      const { closeModal } = useModal.confirm({
        title: '确定删除当前订单吗?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '删除后将不可恢复，请谨慎操作',
        async onOk() {
          let res = await deleteOrder(id)
          if (res.success) {
            message.success('删除成功')
            init()
            closeModal()
          }
        }
      })
    }
    const handleTableChange = (pagination, filters, sorter) => {
      page.current = pagination.current
      page.pageSize = pagination.pageSize
      init()
    }
    const handleTableChange1 = (pagination, filters, sorter) => {
      page1.current = pagination.current
      page1.pageSize = pagination.pageSize
      lookDetail()
    }
    const refund = id => {
      const { closeModal } = useModal.confirm({
        title: '确定退款当前订单吗?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '退款将会原路返回该账户',
        async onOk() {
          let res = await cancelById(3, id)
          if (res.success) {
            message.success('退款成功')
            lookDetail()
            closeModal()
          }
        }
      })
    }
    const confirm = id => {
      const { closeModal } = useModal.confirm({
        title: '确定完成当前订单吗?',
        icon: createVNode(ExclamationCircleOutlined),
        async onOk() {
          let res = await cancelById(2, id)
          if (res.success) {
            message.success('完成订单')
            lookDetail()
            closeModal()
          }
        }
      })
    }
    const selectXZname = e => {
      console.log(e, '选择的是')
      initStreetList()
    }
    //获取街道信息
    initStreetList()
    async function initStreetList() {
      let res = await selectAllshName(data.searchForm.xzName)
      if (res.success) {
        res.object.unshift('全部')
        data.streetList = res.object
      }
    }
    init()
    async function init() {
      // if (data.searchForm.shName == "全部") {
      //   data.searchForm.shName = "";
      // }
      // if (data.searchForm.xzName == "全部") {
      //   data.searchForm.xzName = "";
      // }
      let obj1 = {
        shName: data.searchForm.shName == '全部' ? '' : data.searchForm.shName,
        xzName: data.searchForm.xzName == '全部' ? '' : data.searchForm.xzName
      }
      deleteObjBlank(obj1)
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...obj1,
        keyword: data.searchForm.keyword
      }
      console.log(obj1, 'obj1')

      let res = await selectPromotionOrder(obj)
      if (res.success) {
        data.loading = false
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        page.total = res.object.total
      }
    }

    return {
      ...toRefs(data),
      colums,
      pagination,
      look,
      del,
      openModal,
      addGroup,
      rules,
      searchAddress,
      districtList,
      closeModal,
      pagination1,
      selectTime,
      statusList,
      labelCol: { style: { fontWeight: 'bold', width: '100px' } },
      search,
      searchUser,
      refund,
      colums1,
      confirm,
      orderListStatusColor,
      handleTableChange,
      handleTableChange1,
      orderStatus,
      getDistrictList,
      selectXZname,
      districtList1
    }
  },

  components: {
    ExclamationCircleOutlined
  }
}
</script>

<style scoped lang="less"></style>
